<!-- 用户头像 -->
<script setup>
import pageComponent from '@/components/pageComponent.vue'
import { useUserStore } from '@/stores/counter.js'
import { ref } from 'vue'
import {
  Plus,
  Upload
} from '@element-plus/icons-vue'
import {
  userUpdataImgService,
  userGetUserInfoService
} from '@/api/user.js'
const userStore = useUserStore()
const userpic = ref()
const butFage = ref(true)
userpic.value = userStore.userInof

const imageUrl = ref('')
imageUrl.value = userpic.value.user_pic
const uploadRef = ref()

const onUpdataImg = (uploadFile) => {
  butFage.value = false
  const reader = new FileReader()
  reader.readAsDataURL(uploadFile.raw)
  reader.onload = () => {
    imageUrl.value = reader.result
  }
}

const uploadUserPic = async () => {
  await userUpdataImgService(imageUrl.value)
  ElMessage.success('上传成功！')
  await userGetUserInfoService()
}
</script>

<template>
  <!-- <div>用户头像</div> -->
  <pageComponent title="更换头像">
    <div class="box">
      <div class="img">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :auto-upload="false"
          style="display: flow"
          ref="uploadRef"
          :on-change="onUpdataImg"
        >
          <img :src="imageUrl" class="avatar" />
        </el-upload>
        <el-button
          type="primary"
          class="upLoadButton"
          :icon="Plus"
          @click="
            uploadRef.$el
              .querySelector('input')
              .click()
          "
        >
          选择图片
        </el-button>
        <el-button
          type="success"
          :icon="Upload"
          @click="uploadUserPic"
          :disabled="butFage"
        >
          上传头像
        </el-button>
      </div>
    </div>
  </pageComponent>
</template>

<style scoped>
img {
  width: 200px;
}
</style>
